<template>
  <div class="account-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h3>账号管理</h3>
        <p>管理所有Web3账号信息</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建账号
        </el-button>
      </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-form :model="queryForm" inline>
        <el-form-item label="账号名称">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入账号名称"
            clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="全部状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 账号表格 -->
    <el-table
      v-loading="loading"
      :data="accounts"
      stripe
      class="account-table">

      <el-table-column prop="name" label="账号名称" min-width="150">
        <template #default="{ row }">
          <div class="account-name">
            <el-icon><User /></el-icon>
            <span>{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="激活配置" min-width="150">
        <template #default="{ row }">
          <el-tag v-if="row.activeConfigName" type="success" size="small">
            {{ row.activeConfigName }}
          </el-tag>
          <el-tag v-else type="info" size="small">未配置</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />

      <el-table-column label="配置状态" width="120">
        <template #default="{ row }">
          <StatusTag
            :value="row.activeConfigCount > 0 ? 1 : row.configCount > 0 ? 0 : -1"
            :map="configStatusMap" />
        </template>
      </el-table-column>

      <el-table-column label="Cookies状态" width="100">
        <template #default="{ row }">
          <StatusTag :value="row.hasCookies" :map="cookieStatusMap" />
        </template>
      </el-table-column>

      <el-table-column label="客户端" min-width="160">
        <template #default="{ row }">
          <div class="client-cell" v-if="row.boundClientId">
            <span class="client-id">{{ row.boundClientId }}</span>
            <el-tag size="small" type="success">已绑定</el-tag>
          </div>
          <el-tag v-else type="info">未绑定</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="客户端心跳" width="170">
        <template #default="{ row }">
          {{ formatDateTime(row.clientLastSeenAt) || '--' }}
        </template>
      </el-table-column>

      <el-table-column label="凭证同步" width="170">
        <template #default="{ row }">
          {{ formatDateTime(row.lastCredentialCapturedAt) || '--' }}
        </template>
      </el-table-column>

      <el-table-column prop="status" label="账号状态" width="80">
        <template #default="{ row }">
          <StatusTag :value="row.status" :map="accountStatusMap" />
        </template>
      </el-table-column>

      <el-table-column prop="updatedAt" label="更新时间" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.updatedAt) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-tooltip content="交易记录" placement="top">
            <el-button
              type="info"
              size="small"
              circle
              @click="handleViewTradeLogs(row)">
              <el-icon><View /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip :content="row.boundClientId ? '重启客户端' : '未绑定客户端'" placement="top">
            <el-button
              type="warning"
              size="small"
              circle
              @click="handleRestart(row)">
              <el-icon><RefreshRight /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button
              type="success"
              size="small"
              circle
              @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              type="danger"
              size="small"
              circle
              @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange" />
    </div>

    <el-dialog
      v-model="showTradeDialog"
      :title="activeAccount ? `${activeAccount.name} - 交易记录` : '交易记录'"
      width="900px"
      destroy-on-close
      @close="handleTradeDialogClose">
      <el-table
        :data="tradeLogs"
        size="small"
        border
        v-loading="tradeLogLoading"
        empty-text="暂无交易记录">
        <el-table-column prop="tradeTime" label="时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.tradeTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="direction" label="方向" width="90" />
        <el-table-column prop="plannedAmount" label="计划金额" min-width="120">
          <template #default="{ row }">
            {{ formatAmount(row.plannedAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="actualAmount" label="实际金额" min-width="120">
          <template #default="{ row }">
            {{ formatAmount(row.actualAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="slippage" label="磨损" min-width="120">
          <template #default="{ row }">
            {{ formatAmount(row.slippage) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" />
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-pagination
            v-if="tradeLogPagination.total > tradeLogPagination.size"
            :current-page="tradeLogPagination.page"
            :page-size="tradeLogPagination.size"
            layout="prev, pager, next"
            :total="tradeLogPagination.total"
            @current-change="handleTradeLogPageChange" />
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { http } from '@/utils/request'
import { ElMessageBox, ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import StatusTag from '@/components/StatusTag.vue'
import { useTradeLogStore } from '@/store/tradeLog'

const router = useRouter()
const tradeLogStore = useTradeLogStore()

// 状态
const loading = ref(false)
const accounts = ref([])

// 查询表单
const queryForm = reactive({
  name: '',
  status: null
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const showTradeDialog = ref(false)
const activeAccount = ref(null)
const TRADE_LOG_PAGE_SIZE = 10

const { logs: tradeLogs, pagination: tradeLogPagination, loading: tradeLogLoading } = storeToRefs(tradeLogStore)

const accountStatusMap = {
  1: { text: '启用', type: 'success' },
  0: { text: '禁用', type: 'danger' }
}

const cookieStatusMap = {
  true: { text: '已设置', type: 'success' },
  false: { text: '未设置', type: 'info' }
}

const configStatusMap = {
  1: { text: '有激活配置', type: 'success' },
  0: { text: '未激活', type: 'warning' },
  '-1': { text: '未配置', type: 'info' }
}

// 初始化
onMounted(() => {
  loadAccounts()
})

// 加载账号列表
const loadAccounts = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...queryForm
    }

    const response = await http.get('/accounts', params)
    const { list, total } = response.data

    accounts.value = list
    pagination.total = total
  } catch (error) {
    ElMessage.error('加载账号列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  loadAccounts()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    name: '',
    status: null
  })
  handleQuery()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.page = page
  loadAccounts()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadAccounts()
}

// 新建账号
const handleCreate = () => {
  router.push('/accounts/edit')
}

// 配置管理（核心新功能）
const handleManageConfigs = (row) => {
  router.push(`/accounts/${row.id}/configs`)
}

// 编辑账号
const handleEdit = (row) => {
  router.push(`/accounts/edit/${row.id}`)
}

const loadTradeLogs = async (page = 1) => {
  if (!activeAccount.value) return
  await tradeLogStore.fetchTradeLogs({
    accountId: activeAccount.value.id,
    page,
    size: TRADE_LOG_PAGE_SIZE
  })
}

const handleViewTradeLogs = async (row) => {
  activeAccount.value = { id: row.id, name: row.name }
  tradeLogStore.clearLogs()
  showTradeDialog.value = true
  await loadTradeLogs(1)
}

const handleTradeLogPageChange = async (page) => {
  await loadTradeLogs(page)
}

const handleTradeDialogClose = () => {
  tradeLogStore.clearLogs()
  activeAccount.value = null
  showTradeDialog.value = false
}

// 重启客户端
const handleRestart = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要重启账号 "${row.name}" 的客户端吗？`,
      '确认重启',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await http.post(`/accounts/${row.id}/restart`)
    ElMessage.success('重启指令已发送')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重启失败')
    }
  }
}

// 删除账号
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除账号 "${row.name}" 吗？删除后该账号的所有配置也将被删除，此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await http.delete(`/accounts/${row.id}`)
    ElMessage.success('删除成功')
    loadAccounts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00'
  return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 4 })
}
</script>

<style lang="scss" scoped>
.account-list {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-left {
      h3 {
        margin: 0 0 5px;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .filter-bar {
    margin-bottom: 20px;
    padding: 15px 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .account-table {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .account-name {
      display: flex;
      align-items: center;
      gap: 8px;

      .el-icon {
        color: #409EFF;
      }
    }

    .client-cell {
      display: flex;
      align-items: center;
      gap: 6px;

      .client-id {
        font-family: 'JetBrains Mono', Menlo, Consolas, monospace;
        font-size: 12px;
        color: #4c6ef5;
      }
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    width: 100%;
  }
}
</style>
